/*
 * @Author: your name
 * @Date: 2021-06-24 11:57:16
 * @LastEditTime: 2021-06-24 18:28:56
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /shujucaiji/lib/handler/summary.js
 */
const { Summary, Project, Orientation } = require('../db');
// const control = require('../mock/control');
// const mock1 = require('../mock/mock1');
// const mock2 = require('../mock/mock2');
// const mock3 = require('../mock/mock3');
// const mock4 = require('../mock/mock4');
// const mock5 = require('../mock/mock5');
// const mock6 = require('../mock/mock6');
// const mock7 = require('../mock/mock7');
// const mock8 = require('../mock/mock8');

// // 整理前期模拟数据
const inner = () => {};


// // 写入模拟数据
inner.writeMock = async () => {
  // const combine = [mock1, mock2, mock3, mock4, mock5, mock6, mock7, mock8];
  const combine = [mock1]

  const controlData = control.map(item => {
    const { date, startTime, endTime } = item;
    item.date = new Date(date).getTime();
    item.startTime = new Date(`${date} ${startTime}`);
    item.endTime = new Date(`${date} ${endTime}`);
    item.timeLength = item.endTime - item.startTime;
    return item;
  });

  for(const mock of combine) {
    for(const item of mock) {
      const { date, startTime, endTime } = item;
      item.date = new Date(date).getTime();
      item.startTime = new Date(`${date} ${startTime}`).getTime();
      item.endTime = new Date(`${date} ${endTime}`).getTime();
      item.timeLength = item.endTime - item.startTime;
      if(typeof item.runningForce === 'string' && item.runningForce.includes('-')) {
        item.runningForce = item.runningForce.split('-')[0]
      }

      if(typeof item.rotateForce === 'string' && item.rotateForce.includes('-')) {
        item.rotateForce = item.rotateForce.split('-')[0]
      }

      if(typeof item.landForce === 'string' && item.landForce.includes('-')) {
        item.landForce = item.landForce.split('-')[0]
      }

      const sizuan = controlData.find(o => o.date === item.date);
      if(sizuan) {
        Object.keys(sizuan).forEach(key => {
          if(!item[key]) {
            item[key] = sizuan[key];
          }
        });
      }
      const record = await Summary.findOne({ startTime: item.startTime })
      if(!record) {
        const doc = new Summary({
          ...item
        });
        doc.save().catch(err => console.log(err, item));
      }
    }
    console.log('complete')
  }
}

// inner.writeMock()

// // 写入数据拉取数据
// inner.getRemoteData = async(data) => {
//   if(!data) {
//     return
//   }

//   const {
//     vehId,  // 车辆唯一id
//     currWorkTime, // 当前工作时间
//     slurryPressure,  // 泥浆压力
//     powerHeadFeedSpeed, // 动力头给进速度(是否为行走压力)

//   } = data
// }

const outer = () => {};

// 数据列表信息查询
outer.getRecordList = async(params) => {
  const { projectId, workName, pageNo = 1, pageSize = 10 } = params;
  if(workName === '导向') {
    const total = await Orientation.find({ projectId }).count()
    const skipNum = (Number(pageNo) - 1) * Number(pageSize);
    const limitNum = Number(pageSize);
    const records = await Orientation.find({ projectId }).skip(skipNum).limit(limitNum);
    if(!records) {
      return { 'success': false, 'msg': '查询失败' };
    }
    return { 'success': true, 'msg': '数据列表查询成功', 'data': {records, total}};

  } else {
    const total = await Summary.find({ projectId, workName }).count()
    const skipNum = (Number(pageNo) - 1) * Number(pageSize);
    const limitNum = Number(pageSize);
    const records = await Summary.find({ projectId, workName }).skip(skipNum).limit(limitNum);
    if(!records) {
      return { 'success': false, 'msg': '查询失败' };
    }
    return { 'success': true, 'msg': '数据列表查询成功', 'data': {records, total}};
  }
  
};

// 实时数据查询
outer.getTimingData = async() => {
  const data = await Summary.find({}).sort({startTime: -1}).limit(1);
  if(Date.now() - data.startTime > 5 * 60 * 1000) {
    return {
      sucess: false,
      msg: '暂无数据',
      data: {},
    };
  }
  return {
    success: true,
    'msg': '查询成功',
    data: data,
  };
};

// 更新记录
outer.updateRecord = async(options) => {
  const { type, record } = options
  const { _id } = record
  if(type === '导向') {
    const data = await Orientation.findOne({ _id }).catch(err => console.log(err))
    if(!data) {
      return { success: false, msg: '更新失败,请刷新重试' }
    } 
    const res = await Orientation.updateOne({ _id}, record)
    if(res.ok === 1) {
      return { success: true, msg: '数据更新成功' }
    }
    return { success: false, msg: '更新失败,请刷新重试' }
  } else {
    const data = await Summary.findOne({ _id }).catch(err => console.log(err))
    if(!data) {
      return { success: false, msg: '更新失败,请刷新重试' }
    } 
    const res = await Summary.updateOne({ _id}, record)
    if(res.ok === 1) {
      return { success: true, msg: '数据更新成功' }
    }
    return { success: false, msg: '更新失败,请刷新重试' }
  }
}

// 记录获取数据信息
outer.receiveRecordData = async (options) => {
  const {projectId, workName } = options
  if(!projectId || !workName) {
    return {"success": false, 'msg': '缺少工程信息，请检查确认是否已经选择工程信息及作业信息'}
  }

  const doc = new Summary(options)

  const res = await doc.save()
  return { "success": true, "msg": "信息记录成功"}
}

// 获取图表数据
outer.getChartData = async(options) =>{
  const { projectId } = options
  // 获取项目信息
  const project = await Project.findOne({ projectId }).catch(err => console.log(err))
  if(!project) {
    return { 'success': false, 'msg': '未查询到项目信息'}
  }

  const { sequence } = project // 获取当前项目的工序
  const data = await Summary.find({ 
      projectId 
    }, 
    { 
      'runningForce': 1, 
      'rotateForce': 1, 
      'landForce': 1, 
      'rotateSpeed': 1 ,
      'deepLength': 1,
      'workName': 1
  }).sort({ 'deepLength' : 1 }).catch(err => console.log(err))
  if(!data || data.length < 1) {
    return { "success": false, "msg": '暂无数据'}
  }

  const result = {
    runningForce: [],
    rotateForce: [],
    landForce: [],
    rotateSpeed: []
  }

  let lenOfWork = 1

  for(const item of data) {
    const { 
      workName, 
      runningForce, 
      rotateForce, 
      landForce, 
      rotateSpeed
    } = item

    let deepLength = item.deepLength.toFixed(2)

    // 查询当前深度数据是否已经存在
    let entry = result.runningForce.find(item => item.x === deepLength && item.s === workName)
    if(!entry) {
      result.runningForce.push({
        'x': deepLength,
        'y': runningForce,
        's': workName,
        'unit': 'KN'
      })
    } else {
      if(runningForce > entry.y ) {
        entry.y = runningForce
      }
    }
    
    entry = result.rotateSpeed.find(item => item.x === deepLength && item.s === workName)
    if(!entry) {
      result.rotateSpeed.push({
        'x': deepLength,
        'y': rotateSpeed,
        's': workName,
        'unit': 'R/min'
      })
    } else {
      if(rotateSpeed > entry.y) {
        entry.y = rotateSpeed
      }
    }

    entry = result.rotateForce.find(item => item.x === deepLength && item.s === workName)
    if(!entry) {
      result.rotateForce.push({
        'x': deepLength,
        'y': rotateForce,
        's': workName,
        'unit': 'KN·m'
      })
    } else {
      if(rotateForce > entry.y) {
        entry.y = rotateForce
      }
    }

    entry = result.landForce.find(item => item.x === deepLength && item.s === workName)
    if(!entry) {
      result.landForce.push({
        'x': deepLength,
        'y': landForce,
        's': workName,
        'unit': 'bar'
      })
    } else {
      if(landForce > entry.y) {
        entry.y = landForce
      }
    }
  }
  return { 'success': true, 'msg': '数据查询成功', 'data': result}
}

// 删除数据信息
outer.deleteRecordData = async(options) => {
  const { id, workName } = options

  try {
    let res = null
    if(workName === '导向') {
      res = await Orientation.deleteOne({ '_id': id})
    } else {
      res = await Summary.deleteOne({ '_id': id})
    }
    if(res.deletedCount > 0) {
      return { 'success': true, message: '数据删除成功'}
    }else {
      return { 'success': false, message: '数据删除失败'}
    }
  } catch (error) {
    return { 'success': false, message: '数据删除失败'}
  }
}

module.exports = outer;